var express = require('express');
var router = express.Router();
const { getList, getDetail, newBlog, updateBlog, deleteBlog } = require('../controler/Blog')
const { SuccessModel, ErrorModel } = require('../model/Resmodel')
const loginCheck = require('../middleware/loginCheck')
/* GET home page. */

router.get('/list', loginCheck, function (req, res, next) {
  let author = req.query.author || ''
  let keyword = req.query.keyword || ''
  let result = getList(author, keyword)
  return result.then(listData => {
    res.json(new SuccessModel(listData)
    )
  })
});


router.get('/detail', function (req, res, next) {
  const id = req.query.id
  const result = getDetail(id)
  return result.then(data => {
    res.json(new SuccessModel(data))
  })
})//思路就是再登录后通过获取对应文章的id号，去数据库中查询这个文章的详情，然后再去返回这个数据渲染至前端的界面上


router.post('/new', loginCheck, (req, res, next) => {

  const author = req.session.username
  req.body.author = author//这个是因为我新建博客的时候不可能还把我是谁也传进去吧，所以我需要；
  const blogData = newBlog(req.body)
  return blogData.then(data => {
    res.json(new SuccessModel(data))
  })

})


router.post('/update', loginCheck, (req, res, next) => {

  const upres = updateBlog(req.query.id, req.body)
  return upres.then(val => {
    if (val) {
      res.json(new SuccessModel())
    } else {
      res.json(new ErrorModel('更新博客失败'))
    }
  })
})


router.post('/del', loginCheck, (req, res, next) => {

  const author = req.session.username
  const deletedata = deleteBlog(req.query.id, author)
  return deletedata.then(val => {
    if (val) {
      res.json(new SuccessModel()) //里面不用去传数据是因为对于post请求，我只需要知道我是否操作成功与否，里面的数据我不关注。

    } else {
      res.json(new ErrorModel('删除博客失败'))
    }

  })
})


module.exports = router;